export class AudioManager {
  private audioContext: AudioContext | null = null;
  private isMuted: boolean = false;
  private volume: number = 0.5;

  constructor() {
    try {
      console.log('开始创建音效管理器...');
      this.initAudioContext();
      console.log('音效管理器创建成功');
    } catch (error) {
      console.error('音效管理器创建失败:', error);
      // 即使音效初始化失败，也不应该阻止游戏运行
    }
  }

  // 初始化音频上下文
  private initAudioContext(): void {
    try {
      this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
    } catch (error) {
      console.warn('Web Audio API not supported:', error);
    }
  }

  // 确保音频上下文已启动
  private async ensureAudioContext(): Promise<void> {
    if (!this.audioContext) return;
    
    if (this.audioContext.state === 'suspended') {
      await this.audioContext.resume();
    }
  }

  // 创建音调
  private createTone(frequency: number, duration: number, type: OscillatorType = 'sine'): Promise<void> {
    return new Promise(async (resolve) => {
      if (!this.audioContext || this.isMuted) {
        resolve();
        return;
      }

      await this.ensureAudioContext();

      const oscillator = this.audioContext.createOscillator();
      const gainNode = this.audioContext.createGain();

      oscillator.connect(gainNode);
      gainNode.connect(this.audioContext.destination);

      oscillator.frequency.setValueAtTime(frequency, this.audioContext.currentTime);
      oscillator.type = type;

      // 设置音量包络
      gainNode.gain.setValueAtTime(0, this.audioContext.currentTime);
      gainNode.gain.linearRampToValueAtTime(this.volume * 0.3, this.audioContext.currentTime + 0.01);
      gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + duration);

      oscillator.start(this.audioContext.currentTime);
      oscillator.stop(this.audioContext.currentTime + duration);

      setTimeout(resolve, duration * 1000);
    });
  }

  // 创建复杂音效
  private createComplexSound(notes: { frequency: number; duration: number; delay?: number }[]): void {
    notes.forEach((note, index) => {
      setTimeout(() => {
        this.createTone(note.frequency, note.duration, 'triangle');
      }, (note.delay || 0) + index * 50);
    });
  }

  // 播放水果投放音效
  public playDropSound(): void {
    this.createTone(440, 0.1, 'square');
  }

  // 播放水果合成音效
  public playMergeSound(fruitLevel: number): void {
    // 根据水果等级播放不同音调
    const baseFreq = 220 + fruitLevel * 60;
    
    this.createComplexSound([
      { frequency: baseFreq, duration: 0.1 },
      { frequency: baseFreq * 1.25, duration: 0.1, delay: 50 },
      { frequency: baseFreq * 1.5, duration: 0.15, delay: 100 }
    ]);
  }

  // 播放得分音效
  public playScoreSound(points: number): void {
    const pitch = Math.min(880, 220 + points * 10);
    this.createTone(pitch, 0.2, 'triangle');
  }

  // 播放游戏结束音效
  public playGameOverSound(): void {
    this.createComplexSound([
      { frequency: 220, duration: 0.3 },
      { frequency: 196, duration: 0.3, delay: 200 },
      { frequency: 174, duration: 0.5, delay: 400 }
    ]);
  }

  // 播放新纪录音效
  public playHighScoreSound(): void {
    this.createComplexSound([
      { frequency: 523, duration: 0.15 },
      { frequency: 659, duration: 0.15, delay: 100 },
      { frequency: 784, duration: 0.15, delay: 200 },
      { frequency: 1047, duration: 0.3, delay: 300 }
    ]);
  }

  // 播放按钮点击音效
  public playButtonSound(): void {
    this.createTone(800, 0.05, 'square');
  }

  // 播放背景音乐（简单的循环旋律）
  public playBackgroundMusic(): void {
    if (this.isMuted) return;

    const melody = [
      { frequency: 262, duration: 0.4 }, // C
      { frequency: 294, duration: 0.4 }, // D
      { frequency: 330, duration: 0.4 }, // E
      { frequency: 294, duration: 0.4 }, // D
      { frequency: 262, duration: 0.4 }, // C
      { frequency: 330, duration: 0.4 }, // E
      { frequency: 392, duration: 0.8 }, // G
      { frequency: 0, duration: 0.4 },   // 休止符
    ];

    const playMelody = () => {
      melody.forEach((note, index) => {
        setTimeout(() => {
          if (note.frequency > 0) {
            this.createTone(note.frequency, note.duration * 0.9, 'triangle');
          }
        }, index * note.duration * 1000);
      });

      // 循环播放
      setTimeout(playMelody, melody.length * 400 + 2000);
    };

    playMelody();
  }

  // 设置音量
  public setVolume(volume: number): void {
    this.volume = Math.max(0, Math.min(1, volume));
  }

  // 静音/取消静音
  public toggleMute(): void {
    this.isMuted = !this.isMuted;
  }

  // 获取静音状态
  public getMuted(): boolean {
    return this.isMuted;
  }

  // 获取音量
  public getVolume(): number {
    return this.volume;
  }

  // 销毁音频管理器
  public destroy(): void {
    if (this.audioContext) {
      this.audioContext.close();
    }
  }
}